/**
 * @FilePath     : log_broadcast_sink.cpp
 * @Description  : 日志广播 Sink 实现
 */
#include "log_broadcast_sink.h"
#include <spdlog/spdlog.h>

namespace infrastructure::logging {

// 静态成员初始化
LogBroadcastEmitter* LogBroadcastEmitter::s_instance = nullptr;
std::mutex LogBroadcastEmitter::s_mutex;

LogBroadcastEmitter::LogBroadcastEmitter(QObject* parent)
    : QObject(parent)
{
}

LogBroadcastEmitter* LogBroadcastEmitter::instance()
{
    std::lock_guard<std::mutex> lock(s_mutex);
    if (!s_instance) {
        s_instance = new LogBroadcastEmitter();
    }
    return s_instance;
}

void LogBroadcastEmitter::emitLogEntry(const QDateTime& timestamp, const QString& level,
                                        const QString& source, const QString& message)
{
    // 使用 Qt::QueuedConnection 确保信号在主线程处理
    // 这里直接发射信号，连接时使用 QueuedConnection 即可
    emit logReceived(timestamp, level, source, message);
}

void installLogBroadcastSink()
{
    auto broadcastSink = std::make_shared<LogBroadcastSinkMt>();

    // 获取默认日志器并添加 sink
    auto defaultLogger = spdlog::default_logger();
    if (defaultLogger) {
        defaultLogger->sinks().push_back(broadcastSink);
    }

    // 为所有已注册的日志器添加 sink
    spdlog::apply_all([&broadcastSink](std::shared_ptr<spdlog::logger> logger) {
        // 检查是否已经添加了广播 sink，避免重复
        bool hasBroadcastSink = false;
        for (const auto& sink : logger->sinks()) {
            if (dynamic_cast<LogBroadcastSinkMt*>(sink.get())) {
                hasBroadcastSink = true;
                break;
            }
        }
        if (!hasBroadcastSink) {
            logger->sinks().push_back(broadcastSink);
        }
    });
}

void installLogBroadcastSink(const QString& loggerName)
{
    auto logger = spdlog::get(loggerName.toStdString());
    if (logger) {
        auto broadcastSink = std::make_shared<LogBroadcastSinkMt>();
        logger->sinks().push_back(broadcastSink);
    }
}

} // namespace infrastructure::logging
